#include "NetService.h"

#include "NFCNet.h"
#include "NFCHttpNet.h"


INetService *g_pNetService = NULL;

NetService::NetService()
{
    g_pNetService = this;
}

NetService::~NetService()
{
}

bool NetService::Init()
{
    //CreateHttpServer(nullptr, 1010);
    return true;
}

bool NetService::Shut()
{
    std::list<NFINet*>::iterator it = m_listNet.begin();
    while (it != m_listNet.end())
    {
        (*it)->Final();
        delete (*it);
        ++it;
    }
    m_listNet.clear();

    for (auto item : m_mapHttptNet)
    {
        item.second->Final();
    }
    m_mapHttptNet.clear();
    return true;

}
bool NetService::ReadyExecute()
{
    return true;

}
bool NetService::Execute()
{
    std::list<NFINet*>::iterator it = m_listNet.begin();
    while (it != m_listNet.end())
    {
        (*it)->Execute();
        ++it;
    }

    for (auto item : m_mapHttptNet)
    {
        item.second->Execute();
    }    

    return true;

}

bool NetService::AfterInit()
{
    return true;
}

NFINet* NetService::CreateClient(NET_RECEIVE_FUNCTOR handleRecieve, NET_EVENT_FUNCTOR handleEvent, const char* strIP, const unsigned short nPort)
{
	NFCNet *pNet = new NFCNet(handleRecieve, handleEvent);

	pNet->Initialization(strIP, nPort);

	m_listNet.push_back(pNet);

	return pNet;
}

NFINet* NetService::CreateServer(NET_RECEIVE_FUNCTOR handleRecieve, NET_EVENT_FUNCTOR handleEvent, const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount/* = 4*/)
{
	NFCNet *pNet = new NFCNet(handleRecieve, handleEvent);

	pNet->Initialization(nMaxClient, nPort, nCpuCount);
	
	m_listNet.push_back(pNet);

	return pNet;
}

NFIHttpNet* NetService::CreateHttpServer(HTTPNET_RECEIVE_FUNCTOR handleRecive, unsigned short nPort)
{
    auto itr = m_mapHttptNet.find(nPort);
    if (itr != m_mapHttptNet.end())
    {
        return NULL;
    }

    NFCHttpNet *pNet = new NFCHttpNet(handleRecive);

    pNet->InitServer(nPort);

    m_mapHttptNet.insert(std::make_pair(nPort, pNet));

    return pNet;
}